import { BASE_API } from '@/config'
import { useQuery } from '@tanstack/react-query'

export interface Layout {
  hasNav: boolean
  hasFooter: boolean
  darkMode: boolean
}

export interface Prefix {
  public: string
}

export interface Chain {
  chainId: number
  passport: string
  witness: string
  participate: string
}

export interface Config {
  layout: Layout
  prefix: Prefix
  chain: Chain
}

export interface CommunityLink {
  title: string
  link?: string
}

export interface Community {
  phone: CommunityLink
  email: CommunityLink
  address: CommunityLink
  services: CommunityLink[]
  about: CommunityLink
  news: CommunityLink
  join: CommunityLink
}

export interface AppConfig {
  config: Config
  community: Community
}

const defaultAppConfig: AppConfig = {
  config: {
    layout: {
      hasNav: true,
      hasFooter: true,
      darkMode: true
    },
    prefix: {
      public: ''
    },
    chain: {
      chainId: 1,
      passport: '',
      witness: '共识节点',
      participate: '参与节点'
    }
  },
  community: {
    phone: {
      title: '0551-65302120'
    },
    email: {
      title: 'service@zkjg.com',
      link: 'https://mailto:service@zkjg.com'
    },
    address: {
      title: '安徽省合肥市高新区创新大道与长江西路交口置地创新中心23楼',
      link: 'https://www.amap.com/search?query=安徽省合肥市高新区创新大道与长江西路交口置地创新中心23楼&zoom=12'
    },
    services: [
      {
        title: '晶格BaaS',
        link: 'https://zkjg.com/product/baas'
      },
      {
        title: '晶格DID',
        link: 'https://zkjg.com/product/did'
      },
      {
        title: '晶格区块链可信硬件',
        link: 'https://zkjg.com/product/hard'
      }
    ],
    about: {
      title: '关于晶格',
      link: 'https://zkjg.com/about'
    },
    news: {
      title: '新闻中心',
      link: 'https://zkjg.com/news/us'
    },
    join: {
      title: '加入我们',
      link: 'https://zkjg.com/join'
    }
  }
}
export const useAppConfig = () => {
  const { data } = useQuery<AppConfig>({
    queryKey: ['appConfig'],
    queryFn: async () => {
      try {
        const response = await fetch(`${BASE_API}/config.json`)
        const data = (await response.json()) as AppConfig
        return data
      } catch (error) {
        console.error('获取配置文件失败：', error)
        return defaultAppConfig
      }
    }
  })

  if (!data) {
    return {
      config: defaultAppConfig.config,
      community: defaultAppConfig.community,
      passport: defaultAppConfig.config.chain.passport,
      chain: defaultAppConfig.config.chain
    }
  }

  return {
    config: data.config,
    community: data.community,
    passport: data.config.chain.passport,
    chain: data.config.chain
  }
}
